package models

import (
	"fmt"
	"github.com/astaxie/beego"
	"github.com/astaxie/beego/orm"
	pageUtil "go_upload_file/models/utils"
	"time"
)

// FileUpload 文件上传表结构
type FileUpload struct {
	Id           int       `json:"id" orm:"column(id) bigint pk;auto"`
	Filename     string    `json:"filename" orm:"column(filename) size(128)"`
	Hash         string    `json:"hash" orm:"column(hash) size(128)"`
	Path         string    `json:"path" orm:"column(path) size(128)"`
	CategoryCode string    `json:"categoryCode" orm:"column(category_code) size(20)"`
	Status       int       `json:"status" orm:"column(status)"`
	UploadTime   time.Time `json:"uploadTime" orm:"column(upload_time) type(datetime);"`
}

func (f *FileUpload) TableName() string {
	return "images"
}

// 根据username 和 fileName查询文件的细节
func (f *FileUpload) FindUploadDetailByFileName(username, fileName string) (detail FileUpload, err error) {
	newOrmer := orm.NewOrm()
	err = newOrmer.QueryTable(&FileUpload{}).Filter("username", username).Filter("fileName", fileName).One(&detail)
	return
}

// 图片分页查询
func (f *FileUpload) GetList(pageSize int, pageNum int, category string) ([]FileUpload, error) {
	getOrm := orm.NewOrm()
	var res = make([]FileUpload, 0)
	count, err := getOrm.Raw("select * from images ").QueryRows(&res)
	//1获取数据总数
	qs := getOrm.QueryTable(f.TableName())
	//	总页数
	pageNum = pageUtil.Page(pageSize, pageNum, count)
	_, err = qs.Filter("category_code", category).Limit(pageSize, pageSize*(pageNum-1)).OrderBy("-id").All(&res)
	if err != nil {
		beego.Info("err", err)
		return res, err
	}
	beego.Info("查找成功")
	return res, err
}

// 保存一条记录
func (f *FileUpload) InsertOneRecord() (id int64, err error) {
	id, err = orm.NewOrm().Insert(f)
	return
}

// 更新一列
func (f *FileUpload) UpdateColumn(uploaded string) (num int64, err error) {
	POrmer := orm.NewOrm()
	num, err = POrmer.Update(f, uploaded)
	if err != nil {
		fmt.Printf("fail to update FileUpload cloumn ,columnName:[%v]", uploaded)
		return
	}
	return
}

func NewFileUpload() *FileUpload {
	return &FileUpload{}
}
